{% extends 'base.html' %}
{% load static %}

{% block title %}聊天{% endblock %}

{% block extra_css %}
<style>
    * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
    }
    
    .chat-main-container {
        display: flex;
        height: calc(100vh - 60px);
        background: #f5f5f5;
        overflow: hidden;
    }

    /* 左侧边栏 - 用户和群组列表 */
    .chat-sidebar {
        width: 350px;
        background: #fff;
        border-right: 1px solid #e0e0e0;
        display: flex;
        flex-direction: column;
        overflow: hidden;
    }

    .sidebar-header {
        padding: 25px;
        background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
        color: white;
    }

    .sidebar-header h2 {
        font-size: 20px;
        margin-bottom: 10px;
        display: flex;
        align-items: center;
        gap: 8px;
    }

    /* 标签页样式 */
    .sidebar-tabs {
        display: flex;
        background: white;
        border-bottom: 1px solid #e0e0e0;
    }

    .tab-btn {
        flex: 1;
        padding: 12px;
        border: none;
        background: none;
        cursor: pointer;
        font-size: 14px;
        color: #666;
        border-bottom: 2px solid transparent;
        transition: all 0.3s;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 6px;
    }

    .tab-btn:hover {
        background: #f8f9fa;
        color: #4facfe;
    }

    .tab-btn.active {
        color: #4facfe;
        border-bottom-color: #4facfe;
        font-weight: 600;
    }

    .tab-btn i {
        font-size: 14px;
    }

    .tab-content {
        display: none;
        flex: 1;
        overflow-y: auto;
    }

    .tab-content.active {
        display: block;
    }

    .search-box {
        position: relative;
    }

    .search-box input {
        width: 100%;
        padding: 8px 35px 8px 12px;
        border: none;
        border-radius: 20px;
        background: rgba(255, 255, 255, 0.2);
        color: white;
        font-size: 14px;
    }

    .search-box input::placeholder {
        color: rgba(255, 255, 255, 0.7);
    }

    .search-box i {
        position: absolute;
        right: 12px;
        top: 50%;
        transform: translateY(-50%);
        color: rgba(255, 255, 255, 0.7);
    }

    .conversation-list {
        flex: 1;
        overflow-y: auto;
        padding: 10px 0;
    }

    .conversation-item {
        display: flex;
        align-items: center;
        padding: 12px 20px;
        cursor: pointer;
        transition: background 0.2s;
        border-left: 3px solid transparent;
    }

    .conversation-item:hover {
        background: #f8f9fa;
    }

    .conversation-item.active {
        background: #e8f0fe;
        border-left-color: #667eea;
    }

    .conversation-avatar {
        width: 48px;
        height: 48px;
        border-radius: 50%;
        margin-right: 12px;
        object-fit: cover;
        flex-shrink: 0;
    }

    .conversation-info {
        flex: 1;
        min-width: 0;
    }

    .conversation-name {
        font-size: 15px;
        font-weight: 600;
        color: #333;
        margin-bottom: 4px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }

    .conversation-preview {
        font-size: 13px;
        color: #999;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }

    .conversation-meta {
        display: flex;
        flex-direction: column;
        align-items: flex-end;
        flex-shrink: 0;
    }

    .conversation-time {
        font-size: 11px;
        color: #999;
        margin-bottom: 4px;
    }

    .unread-badge {
        background: #ff4757;
        color: white;
        border-radius: 10px;
        padding: 2px 8px;
        font-size: 11px;
        font-weight: bold;
        min-width: 20px;
        text-align: center;
    }

    /* 右侧聊天区域 */
    .chat-area {
        flex: 1;
        display: flex;
        flex-direction: column;
        background: #fff;
        overflow: hidden;
    }

    .chat-area.empty {
        justify-content: center;
        align-items: center;
        background: #f8f9fa;
    }

    .empty-chat {
        text-align: center;
        color: #999;
    }

    .empty-chat i {
        font-size: 64px;
        color: #ddd;
        margin-bottom: 20px;
    }

    .empty-chat h3 {
        font-size: 20px;
        margin-bottom: 10px;
    }

    .chat-header {
        padding: 15px 24px;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        display: flex;
        align-items: center;
        justify-content: space-between;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    }

    .chat-header-left {
        display: flex;
        align-items: center;
    }

    .chat-header-avatar {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        margin-right: 12px;
        object-fit: cover;
    }

    .chat-header-info h3 {
        font-size: 16px;
        margin-bottom: 2px;
    }

    .chat-header-info p {
        font-size: 12px;
        opacity: 0.8;
    }

    .chat-messages {
        flex: 1;
        overflow-y: auto;
        padding: 20px;
        background: linear-gradient(to bottom, #f8f9fa 0%, #e9ecef 100%);
    }

    .message {
        display: flex;
        margin-bottom: 16px;
        animation: slideIn 0.3s ease;
    }

    .message.sent {
        justify-content: flex-end;
    }

    .message.received {
        justify-content: flex-start;
    }

    .message-wrapper {
        max-width: 60%;
        display: flex;
        flex-direction: column;
    }

    .message.sent .message-wrapper {
        align-items: flex-end;
    }

    .message.received .message-wrapper {
        align-items: flex-start;
    }

    .message-bubble {
        padding: 12px 16px;
        border-radius: 18px;
        word-wrap: break-word;
        box-shadow: 0 1px 2px rgba(0,0,0,0.1);
        position: relative;
    }

    .message.sent .message-bubble {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border-bottom-right-radius: 4px;
    }

    .message.received .message-bubble {
        background: white;
        color: #333;
        border-bottom-left-radius: 4px;
    }

    .message-time {
        font-size: 11px;
        color: #999;
        margin-top: 4px;
        padding: 0 4px;
    }

    .message.sent .message-time {
        color: rgba(255, 255, 255, 0.7);
    }

    .chat-input-container {
        padding: 16px 20px;
        background: white;
        border-top: 1px solid #e0e0e0;
        display: flex;
        align-items: center;
        gap: 12px;
    }

    .chat-input {
        flex: 1;
        border: 2px solid #e8e8e8;
        border-radius: 24px;
        padding: 10px 18px;
        font-size: 14px;
        outline: none;
        transition: all 0.3s;
        background: #f8f9fa;
    }

    .chat-input:focus {
        border-color: #667eea;
        background: white;
        box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
    }

    .send-btn {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border: none;
        border-radius: 50%;
        width: 44px;
        height: 44px;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        transition: all 0.3s;
        box-shadow: 0 2px 8px rgba(102, 126, 234, 0.4);
    }

    .send-btn:hover {
        transform: scale(1.05);
        box-shadow: 0 4px 12px rgba(102, 126, 234, 0.6);
    }

    .send-btn:active {
        transform: scale(0.95);
    }

    .send-btn:disabled {
        background: #ccc;
        cursor: not-allowed;
        box-shadow: none;
    }

    @keyframes slideIn {
        from {
            opacity: 0;
            transform: translateY(10px);
        }
        to {
            opacity: 1;
            transform: translateY(0);
        }
    }

    /* 滚动条样式 */
    .conversation-list::-webkit-scrollbar,
    .chat-messages::-webkit-scrollbar {
        width: 6px;
    }

    .conversation-list::-webkit-scrollbar-track,
    .chat-messages::-webkit-scrollbar-track {
        background: #f1f1f1;
    }

    .conversation-list::-webkit-scrollbar-thumb,
    .chat-messages::-webkit-scrollbar-thumb {
        background: #ccc;
        border-radius: 3px;
    }

    .conversation-list::-webkit-scrollbar-thumb:hover,
    .chat-messages::-webkit-scrollbar-thumb:hover {
        background: #999;
    }

    .empty-conversations {
        text-align: center;
        padding: 40px 20px;
        color: #999;
    }

    .empty-conversations i {
        font-size: 48px;
        color: #ddd;
        margin-bottom: 16px;
    }

    /* 好友和群组样式 */
    .action-buttons {
        padding: 15px;
        border-bottom: 1px solid #e0e0e0;
        display: flex;
        gap: 10px;
    }

    .action-btn {
        flex: 1;
        padding: 8px 12px;
        border: 1px solid #667eea;
        background: white;
        color: #667eea;
        border-radius: 6px;
        cursor: pointer;
        font-size: 13px;
        transition: all 0.3s;
    }

    .action-btn:hover {
        background: #667eea;
        color: white;
    }

    .action-btn i {
        margin-right: 4px;
    }

    .friend-item, .group-item {
        display: flex;
        align-items: center;
        padding: 12px 20px;
        cursor: pointer;
        transition: background 0.2s;
        border-bottom: 1px solid #f0f0f0;
    }

    .friend-item:hover, .group-item:hover {
        background: #f8f9fa;
    }

    .friend-avatar, .group-avatar {
        width: 42px;
        height: 42px;
        border-radius: 50%;
        margin-right: 12px;
        object-fit: cover;
    }

    .friend-info, .group-info {
        flex: 1;
    }

    .friend-name, .group-name {
        font-weight: 500;
        margin-bottom: 2px;
    }

    .friend-status, .group-members {
        font-size: 12px;
        color: #999;
    }

    .friend-actions {
        display: flex;
        gap: 8px;
    }

    .friend-action-btn {
        padding: 4px 12px;
        border: 1px solid #ddd;
        background: white;
        border-radius: 4px;
        font-size: 12px;
        cursor: pointer;
        transition: all 0.2s;
    }

    .friend-action-btn:hover {
        background: #f0f0f0;
    }

    .friend-action-btn.primary {
        background: #667eea;
        color: white;
        border-color: #667eea;
    }

    .friend-action-btn.primary:hover {
        background: #5568d3;
    }

    /* 聊天操作按钮样式 */
    .chat-header-actions {
        display: flex;
        gap: 12px;
        align-items: center;
    }

    .chat-action-btn {
        display: flex;
        align-items: center;
        gap: 6px;
        padding: 8px 16px;
        border: none;
        border-radius: 8px;
        font-size: 14px;
        font-weight: 500;
        cursor: pointer;
        transition: all 0.3s ease;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }

    .chat-action-btn i {
        font-size: 16px;
    }

    .btn-view-profile {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
    }

    .btn-view-profile:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
    }

    .btn-delete-chat {
        background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
        color: white;
    }

    .btn-delete-chat:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(245, 87, 108, 0.4);
    }

    .chat-action-btn:active {
        transform: translateY(0);
    }

    /* 群组操作按钮美化样式 */
    .group-action-btn {
        display: inline-flex;
        align-items: center;
        gap: 8px;
        padding: 10px 18px;
        border: none;
        border-radius: 10px;
        font-size: 14px;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.3s ease;
        box-shadow: 0 2px 8px rgba(0,0,0,0.12);
        position: relative;
        overflow: hidden;
    }

    .group-action-btn::before {
        content: '';
        position: absolute;
        top: 0;
        left: -100%;
        width: 100%;
        height: 100%;
        background: rgba(255, 255, 255, 0.2);
        transition: left 0.5s ease;
    }

    .group-action-btn:hover::before {
        left: 100%;
    }

    .group-action-btn i {
        font-size: 16px;
        transition: transform 0.3s ease;
    }

    .group-action-btn:hover i {
        transform: scale(1.1);
    }

    .group-action-btn:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 16px rgba(0,0,0,0.2);
    }

    .group-action-btn:active {
        transform: translateY(0);
        box-shadow: 0 2px 8px rgba(0,0,0,0.12);
    }

    .btn-invite-member {
        background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
        color: white;
    }

    .btn-invite-member:hover {
        box-shadow: 0 4px 16px rgba(79, 172, 254, 0.5);
    }

    .btn-member-settings {
        background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
        color: white;
    }

    .btn-member-settings:hover {
        box-shadow: 0 4px 16px rgba(250, 112, 154, 0.5);
    }

    .btn-group-settings {
        background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
        color: #333;
    }

    .btn-group-settings:hover {
        box-shadow: 0 4px 16px rgba(168, 237, 234, 0.5);
    }

    .chat-header-actions {
        display: flex;
        gap: 12px;
        align-items: center;
        flex-wrap: wrap;
    }

    /* 模态框样式 */
    .modal {
        display: none;
        position: fixed;
        z-index: 1000;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        background: rgba(0,0,0,0.5);
        animation: fadeIn 0.3s;
    }

    .modal.active {
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .modal-content {
        background: white;
        border-radius: 12px;
        padding: 24px;
        width: 90%;
        max-width: 500px;
        max-height: 80vh;
        overflow-y: auto;
        animation: slideUp 0.3s;
    }

    .modal-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
    }

    .modal-header h3 {
        font-size: 18px;
        color: #333;
    }

    .modal-close {
        background: none;
        border: none;
        font-size: 24px;
        color: #999;
        cursor: pointer;
        padding: 0;
        width: 30px;
        height: 30px;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .modal-close:hover {
        color: #333;
    }

    .form-group {
        margin-bottom: 16px;
    }

    .form-group label {
        display: block;
        margin-bottom: 6px;
        font-size: 14px;
        color: #555;
        font-weight: 500;
    }

    .form-group input,
    .form-group textarea {
        width: 100%;
        padding: 10px 12px;
        border: 1px solid #ddd;
        border-radius: 6px;
        font-size: 14px;
        transition: border-color 0.3s;
    }

    .form-group input:focus,
    .form-group textarea:focus {
        outline: none;
        border-color: #667eea;
    }

    .form-group textarea {
        resize: vertical;
        min-height: 80px;
    }

    .search-results {
        max-height: 300px;
        overflow-y: auto;
        margin-top: 10px;
    }

    .search-result-item {
        display: flex;
        align-items: center;
        padding: 10px;
        border: 1px solid #e0e0e0;
        border-radius: 6px;
        margin-bottom: 8px;
        cursor: pointer;
        transition: all 0.2s;
    }

    .search-result-item:hover {
        background: #f8f9fa;
        border-color: #667eea;
    }

    .search-result-item.selected {
        background: #e8f0fe;
        border-color: #667eea;
    }

    .search-result-avatar {
        width: 36px;
        height: 36px;
        border-radius: 50%;
        margin-right: 10px;
    }

    .search-result-info {
        flex: 1;
    }

    .search-result-name {
        font-weight: 500;
        margin-bottom: 2px;
    }

    .search-result-username {
        font-size: 12px;
        color: #999;
    }

    .submit-btn {
        width: 100%;
        padding: 12px;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border: none;
        border-radius: 6px;
        font-size: 15px;
        font-weight: 500;
        cursor: pointer;
        transition: all 0.3s;
    }

    .submit-btn:hover {
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
    }

    .submit-btn:disabled {
        background: #ccc;
        cursor: not-allowed;
        transform: none;
    }

    /* 好友请求徽章 */
    .request-badge {
        position: absolute;
        top: -5px;
        right: -5px;
        background: #ff4444;
        color: white;
        border-radius: 10px;
        padding: 2px 6px;
        font-size: 11px;
        font-weight: bold;
    }

    .action-btn {
        position: relative;
    }

    /* 好友请求项 */
    .request-item {
        display: flex;
        align-items: center;
        padding: 12px;
        background: white;
        border-radius: 8px;
        margin-bottom: 10px;
        box-shadow: 0 1px 3px rgba(0,0,0,0.1);
    }

    .request-avatar {
        width: 48px;
        height: 48px;
        border-radius: 50%;
        margin-right: 12px;
    }

    .request-info {
        flex: 1;
    }

    .request-name {
        font-weight: 500;
        margin-bottom: 4px;
    }

    .request-time {
        font-size: 12px;
        color: #999;
    }

    .request-actions {
        display: flex;
        gap: 8px;
    }

    .request-btn {
        padding: 6px 16px;
        border: none;
        border-radius: 6px;
        font-size: 13px;
        cursor: pointer;
        transition: all 0.2s;
    }

    .request-btn.accept {
        background: #28a745;
        color: white;
    }

    .request-btn.accept:hover {
        background: #218838;
    }

    .request-btn.reject {
        background: #dc3545;
        color: white;
    }

    .request-btn.reject:hover {
        background: #c82333;
    }

    @keyframes fadeIn {
        from { opacity: 0; }
        to { opacity: 1; }
    }

    @keyframes slideUp {
        from {
            transform: translateY(20px);
            opacity: 0;
        }
        to {
            transform: translateY(0);
            opacity: 1;
        }
    }

    /* 通知列表样式 */
    .notifications-list {
        flex: 1;
        overflow-y: auto;
        padding: 10px 0;
    }

    .notifications-list .conversation-item {
        cursor: pointer;
        border-left: 3px solid transparent;
    }

    .notifications-list .conversation-item.unread {
        background: #f8f9fa;
        border-left-color: #667eea;
    }

    .notifications-list .conversation-item:hover {
        background: #e8f0fe;
    }

    /* 通知详情样式 */
    .notification-detail-content {
        padding: 20px;
        max-width: 800px;
        margin: 0 auto;
    }

    .notification-detail-content h3 {
        color: #333;
        margin-bottom: 10px;
        font-size: 24px;
    }

    .notification-time {
        color: #666;
        font-size: 14px;
        margin-bottom: 20px;
        padding-bottom: 15px;
        border-bottom: 1px solid #e0e0e0;
    }

    .notification-message {
        font-size: 16px;
        line-height: 1.6;
        color: #333;
        margin-bottom: 30px;
        background: #f8f9fa;
        padding: 15px;
        border-radius: 8px;
        border-left: 4px solid #667eea;
    }

    .notification-activity {
        margin-bottom: 25px;
        padding: 20px;
        background: #fff;
        border-radius: 8px;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }

    .notification-activity h4 {
        color: #667eea;
        margin-bottom: 15px;
        font-size: 18px;
    }

    .activity-info p {
        margin-bottom: 8px;
        line-height: 1.5;
    }

    .activity-info strong {
        color: #555;
        min-width: 80px;
        display: inline-block;
    }

    .notification-admin {
        padding: 15px;
        background: #e8f5e8;
        border-radius: 6px;
        border-left: 4px solid #28a745;
    }

    .notification-actions {
        display: flex;
        gap: 10px;
    }

    /* 红点样式 */
    .red-dot {
        display: inline-block;
        width: 8px;
        height: 8px;
        background-color: #ff4757;
        border-radius: 50%;
        margin-right: 8px;
        animation: pulse 1.5s infinite;
    }

    /* 红点脉冲动画 */
    @keyframes pulse {
        0% {
            transform: scale(0.95);
            box-shadow: 0 0 0 0 rgba(255, 71, 87, 0.7);
        }
        70% {
            transform: scale(1);
            box-shadow: 0 0 0 6px rgba(255, 71, 87, 0);
        }
        100% {
            transform: scale(0.95);
            box-shadow: 0 0 0 0 rgba(255, 71, 87, 0);
        }
    }

    /* 未读通知的标题样式 */
    .notification-title.unread {
        font-weight: 600;
        color: #333;
    }

    .notification-title.read {
        color: #666;
        font-weight: normal;
    }

    /* 删除确认模态框样式 */
    .confirm-modal .modal-content {
        max-width: 400px;
    }

    .confirm-actions {
        display: flex;
        gap: 10px;
        margin-top: 20px;
    }

    .confirm-btn {
        flex: 1;
        padding: 10px;
        border: none;
        border-radius: 6px;
        cursor: pointer;
        font-weight: 500;
        transition: all 0.3s;
    }

    .confirm-btn.cancel {
        background: #f8f9fa;
        color: #333;
        border: 1px solid #ddd;
    }

    .confirm-btn.cancel:hover {
        background: #e9ecef;
    }

    .confirm-btn.delete {
        background: #ff4757;
        color: white;
    }

    .confirm-btn.delete:hover {
        background: #ff3742;
        transform: translateY(-1px);
    }

    /* 标签页红点样式 */
    .tab-badge {
        position: absolute;
        top: -5px;
        right: -5px;
        background: #ff4757;
        color: white;
        border-radius: 10px;
        padding: 2px 6px;
        font-size: 11px;
        font-weight: bold;
        min-width: 18px;
        text-align: center;
        line-height: 1;
    }

    .tab-btn {
        position: relative;
        flex: 1;
        padding: 12px;
        border: none;
        background: none;
        cursor: pointer;
        font-size: 14px;
        color: #666;
        border-bottom: 2px solid transparent;
        transition: all 0.3s;
    }
</style>
{% endblock %}

{% block content %}
<div class="chat-main-container">
    <!-- 左侧边栏 -->
    <div class="chat-sidebar">
        <div class="sidebar-header">
            <div class="search-box">
                <input type="text" id="search-input" placeholder="搜索联系人...">
                <i class="fas fa-search"></i>
            </div>
        </div>

        <!-- 标签页切换 -->
        <div class="sidebar-tabs">
            <button class="tab-btn active" data-tab="conversations">
                消息
                <span class="tab-badge" id="conversations-badge" style="display: none;"></span>
            </button>
            <button class="tab-btn" data-tab="friends">
                <i class="fas fa-user-friends"></i> 好友
                <span class="tab-badge" id="friends-badge" style="display: none;"></span>
            </button>
            <button class="tab-btn" data-tab="groups">
                群组
                <span class="tab-badge" id="groups-badge" style="display: none;"></span>
            </button>
            <button class="tab-btn" data-tab="notifications">
                系统通知
                <span class="tab-badge" id="notifications-badge" style="display: none;"></span>
            </button>
        </div>

        <!-- 消息列表 -->
        <div class="tab-content active conversation-list" id="conversations-tab">
            {% if conversations %}
                {% for conv in conversations %}
                <div class="conversation-item"
                     data-conversation-id="{{ conv.conversation_id }}"
                     data-user-id="{{ conv.other_user.id }}"
                     data-user-name="{{ conv.other_user.nickname|default:conv.other_user.username }}">
                    <img src="{% if conv.other_user.avatar %}{{ conv.other_user.avatar }}{% else %}{% static 'imgs/default-avatar.jpg' %}{% endif %}"
                         alt="{{ conv.other_user.nickname }}"
                         class="conversation-avatar">
                    <div class="conversation-info">
                        <div class="conversation-name">{{ conv.other_user.nickname|default:conv.other_user.username }}</div>
                        <div class="conversation-preview">{{ conv.last_message.content|default:"开始对话..." }}</div>
                    </div>
                    <div class="conversation-meta">
                        {% if conv.last_message %}
                        <div class="conversation-time">{{ conv.last_message.created_at|date:"m-d H:i" }}</div>
                        {% endif %}
                        {% if conv.unread_count > 0 %}
                        <span class="unread-badge">{{ conv.unread_count }}</span>
                        {% endif %}
                    </div>
                </div>
                {% endfor %}
            {% else %}
                <div class="empty-conversations">
                    <i class="fas fa-comments"></i>
                    <p>暂无对话</p>
                    <p style="font-size: 12px; margin-top: 8px;">
                        <a href="{% url 'social:user_list' %}" style="color: #667eea;">开始新对话</a>
                    </p>
                </div>
            {% endif %}
        </div>

        <!-- 好友列表 -->
        <div class="tab-content" id="friends-tab">
            <div class="action-buttons">
                <button class="action-btn" onclick="showSearchFriendModal()">
                    添加好友
                </button>
                <button class="action-btn" onclick="showFriendRequestsModal()">
                    <i class="fas fa-user-clock"></i> 好友请求
                    <span id="friend-request-badge" class="request-badge" style="display: none;"></span>
                </button>
            </div>
            <div id="friend-requests-section" style="display: none; padding: 15px; background: #fff3cd; border-bottom: 1px solid #e0e0e0;">
                <!-- 好友请求将在这里显示 -->
            </div>
            <div id="friends-list">
                <!-- 好友列表将通过JavaScript动态加载 -->
            </div>
        </div>

        <!-- 群组列表 -->
        <div class="tab-content" id="groups-tab">
            <div class="action-buttons">
                <button class="action-btn" onclick="showCreateGroupModal()">
                    创建群组
                </button>
            </div>
            <div id="groups-list">
                <!-- 群组列表将通过JavaScript动态加载 -->
            </div>
        </div>
       <!-- 系统通知内容区域 -->
        <div class="tab-content" id="notifications-tab">
            <div class="action-buttons">
                <button class="action-btn" onclick="markAllNotificationsAsRead()">
                    <i class="fas fa-check-double"></i> 全部标记为已读
                </button>
                <button class="action-btn" onclick="deleteAllNotifications()" style="background: #ff4757; color: white; border-color: #ff4757;">
                    删除全部系统消息
                </button>
            </div>
            <div id="notifications-list" class="notifications-list">
                <!-- 系统通知列表将通过JavaScript动态加载 -->
            </div>
        </div>
    </div>

    <!-- 右侧聊天区域 -->
    <div class="chat-area empty" id="chat-area">
        <div class="empty-chat">
            <i class="fas fa-comment-dots"></i>
            <h3>选择一个对话</h3>
            <p>从左侧选择一个联系人开始聊天</p>
        </div>
    </div>
</div>

<!-- 搜索好友模态框 -->
<div class="modal" id="searchFriendModal">
    <div class="modal-content">
        <div class="modal-header">
            <h3>添加好友</h3>
            <button class="modal-close" onclick="closeSearchFriendModal()">&times;</button>
        </div>
        <div class="form-group">
            <label>搜索用户</label>
            <input type="text" id="friend-search-input" placeholder="输入用户名或昵称搜索...">
        </div>
        <div class="search-results" id="friend-search-results">
            <!-- 搜索结果将在这里显示 -->
        </div>
    </div>
</div>

<!-- 好友请求模态框 -->
<div class="modal" id="friendRequestsModal">
    <div class="modal-content">
        <div class="modal-header">
            <h3>好友请求</h3>
            <button class="modal-close" onclick="closeFriendRequestsModal()">&times;</button>
        </div>
        <div style="margin-bottom: 20px;">
            <h4 style="font-size: 15px; color: #666; margin-bottom: 10px;">收到的请求</h4>
            <div id="received-requests">
                <!-- 收到的好友请求将在这里显示 -->
            </div>
        </div>
        <div>
            <h4 style="font-size: 15px; color: #666; margin-bottom: 10px;">发送的请求</h4>
            <div id="sent-requests">
                <!-- 发送的好友请求将在这里显示 -->
            </div>
        </div>
    </div>
</div>

<!-- 创建群组模态框 -->
<div class="modal" id="createGroupModal">
    <div class="modal-content">
        <div class="modal-header">
            <h3>创建群组</h3>
            <button class="modal-close" onclick="closeCreateGroupModal()">&times;</button>
        </div>
        <div class="form-group">
            <label>群组名称 *</label>
            <input type="text" id="group-name-input" placeholder="输入群组名称" required>
        </div>
        <div class="form-group">
            <label>群组描述</label>
            <textarea id="group-description-input" placeholder="输入群组描述（可选）"></textarea>
        </div>
        <div class="form-group">
            <label>添加成员</label>
            <input type="text" id="group-member-search" placeholder="搜索要添加的好友...">
        </div>
        <div class="search-results" id="group-member-results">
            <!-- 好友列表将在这里显示 -->
        </div>
        <div id="selected-members" style="margin: 10px 0;">
            <!-- 已选择的成员将在这里显示 -->
        </div>
        <button class="submit-btn" onclick="createGroup()">创建群组</button>
    </div>
</div>

<script>
// 全局变量
let selectedGroupMembers = [];
let currentConversationId = null;
let currentGroupId = null;
let currentChatType = null; // 'conversation' 或 'group'
let chatSocket = null;
// notificationSocket 已在 base.html 中声明

// 工具函数
function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

function formatMessageTime(isoString) {
    const date = new Date(isoString);
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    return `${month}-${day} ${hours}:${minutes}`;
}

function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

document.addEventListener('DOMContentLoaded', function() {
    let currentUserId = null;

    const chatArea = document.getElementById('chat-area');
    const conversationItems = document.querySelectorAll('.conversation-item');
    const searchInput = document.getElementById('search-input');

     // 初始化所有标签页红点
    updateAllTabBadges();

    // 启动自动刷新时也更新红点
    startAutoRefresh();
    // 标签页切换
const tabBtns = document.querySelectorAll('.tab-btn');
tabBtns.forEach(btn => {
    btn.addEventListener('click', function() {
        const tabName = this.getAttribute('data-tab');

        // 更新按钮状态
        tabBtns.forEach(b => b.classList.remove('active'));
        this.classList.add('active');

        // 更新内容显示
        document.querySelectorAll('.tab-content').forEach(content => {
            content.classList.remove('active');
        });
        document.getElementById(tabName + '-tab').classList.add('active');

        // 点击标签页时隐藏对应的红点
        hideTabDot(tabName);

        // 加载对应数据
        if (tabName === 'friends') {
            loadFriendsList();
        } else if (tabName === 'groups') {
            loadGroupsList();
        } else if (tabName === 'notifications') {
            loadSystemNotifications();
        }
    });
});

// 隐藏指定标签页的红点
function hideTabDot(tabName) {
    const dot = document.getElementById(`${tabName}-dot`);
    if (dot) {
        dot.style.display = 'none';
    }

    // 根据标签页类型执行特定的标记已读操作
    switch(tabName) {
        case 'notifications':
            // 标记所有通知为已读
            markAllNotificationsAsReadSilent();
            break;
        case 'friends':
            // 这里可以添加标记好友请求为已处理的逻辑
            // 暂时只隐藏红点，不修改后端状态
            break;
        case 'conversations':
            // 这里可以添加标记所有会话为已读的逻辑
            // 暂时只隐藏红点，不修改后端状态
            break;
        case 'groups':
            // 群组红点逻辑
            break;
    }
}

    // 搜索功能
    searchInput.addEventListener('input', function(e) {
        const searchTerm = e.target.value.toLowerCase();
        conversationItems.forEach(item => {
            const userName = item.getAttribute('data-user-name').toLowerCase();
            if (userName.includes(searchTerm)) {
                item.style.display = 'flex';
            } else {
                item.style.display = 'none';
            }
        });
    });

    // 点击会话项
    conversationItems.forEach(item => {
        item.addEventListener('click', function() {
            const conversationId = this.getAttribute('data-conversation-id');
            const userId = this.getAttribute('data-user-id');

            // 更新选中状态
            conversationItems.forEach(i => i.classList.remove('active'));
            this.classList.add('active');

            // 加载聊天内容
            loadChat(conversationId, userId);
        });
    });

    function loadChat(conversationId, userId) {
        currentConversationId = conversationId;
        currentGroupId = null;
        currentChatType = 'conversation';
        currentUserId = userId;

        // 关闭之前的WebSocket连接
        if (chatSocket) {
            chatSocket.close();
        }

        // 加载聊天界面
        fetch(`/social/chat/content/${conversationId}/`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    renderChatArea(data);
                    connectWebSocket(conversationId);
                }
            })
            .catch(error => {
                console.error('加载聊天失败:', error);
            });
    }

    window.loadChat = loadChat; // 暴露给全局使用

    function renderMessages(messages) {
        if (!messages || messages.length === 0) {
            return '<div style="text-align: center; color: #999; padding: 40px;">暂无消息</div>';
        }

        const currentUserId = {{ request.user.id }};
        return messages.map(msg => {
            const isSent = msg.sender_id === currentUserId;
            const messageClass = isSent ? 'sent' : 'received';
            const time = formatMessageTime(msg.created_at);

            return `
                <div class="message ${messageClass}" data-message-id="${msg.id}">
                    <div class="message-wrapper">
                        <div class="message-bubble">
                            ${escapeHtml(msg.content)}
                        </div>
                        <div class="message-time">${time}</div>
                    </div>
                </div>
            `;
        }).join('');
    }

    function formatMessageTime(isoString) {
        const date = new Date(isoString);
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        return `${month}-${day} ${hours}:${minutes}`;
    }

    function renderChatArea(data) {
        const { other_user, messages } = data;

        chatArea.classList.remove('empty');
        chatArea.innerHTML = `
            <div class="chat-header">
                <div class="chat-header-left">
                    <img src="${other_user.avatar || '/static/imgs/default-avatar.jpg'}"
                     alt="${other_user.nickname}"
                     class="chat-header-avatar"
                     onerror="this.src='/static/imgs/default-avatar.jpg'">
                    <div class="chat-header-info">
                        <h3>${other_user.nickname || other_user.username}</h3>
                        <p>在线</p>
                    </div>
                </div>
                <div class="chat-header-actions">
                    <button class="chat-action-btn btn-view-profile" onclick="window.location.href='/social/friends/profile/${other_user.id}/'">
                        <i class="fas fa-user-circle"></i>
                        <span>查看主页</span>
                    </button>
                    <button class="chat-action-btn btn-delete-chat" onclick="deleteChatHistory(${currentConversationId})">
                        <i class="fas fa-trash-alt"></i>
                        <span>删除记录</span>
                    </button>
                </div>
            </div>

            <div class="chat-messages" id="chat-messages">
                ${renderMessages(messages)}
            </div>

            <div class="chat-input-container">
                <input type="text"
                       class="chat-input"
                       id="message-input"
                       placeholder="输入消息..."
                       maxlength="1000">
                <button class="send-btn" id="send-btn" disabled>
                    <i class="fas fa-paper-plane"></i>
                </button>
            </div>
        `;

        // 绑定输入框和发送按钮事件
        const messageInput = document.getElementById('message-input');
        const sendBtn = document.getElementById('send-btn');
        const chatMessages = document.getElementById('chat-messages');

        messageInput.addEventListener('input', function() {
            sendBtn.disabled = !this.value.trim();
        });

        messageInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter' && !e.shiftKey && this.value.trim()) {
                e.preventDefault();
                sendMessage();
            }
        });

        sendBtn.addEventListener('click', sendMessage);

        // 滚动到底部
        chatMessages.scrollTop = chatMessages.scrollHeight;
    }

    function connectWebSocket(conversationId) {
        const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
        const wsUrl = `${protocol}//${window.location.host}/ws/chat/${conversationId}/`;

        chatSocket = new WebSocket(wsUrl);

        chatSocket.onopen = function(e) {
            console.log('WebSocket连接已建立');
        };

        chatSocket.onmessage = function(e) {
            const data = JSON.parse(e.data);

            if (data.type === 'chat_message') {
                addMessage(data.message);
            }
        };

        chatSocket.onclose = function(e) {
            console.log('WebSocket连接已关闭');
        };

        chatSocket.onerror = function(e) {
            console.error('WebSocket错误:', e);
        };
    }

    function sendMessage() {
        const messageInput = document.getElementById('message-input');
        const content = messageInput.value.trim();

        if (!content || !currentConversationId) return;

        // 优先使用WebSocket发送消息
        if (chatSocket && chatSocket.readyState === WebSocket.OPEN) {
            chatSocket.send(JSON.stringify({
                type: 'chat_message',
                message: content
            }));
            messageInput.value = '';
            document.getElementById('send-btn').disabled = true;
        } else {
            // WebSocket未连接时降级使用HTTP API
            fetch(`/social/conversations/${currentConversationId}/send/`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': getCookie('csrftoken')
                },
                body: JSON.stringify({ content: content })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    messageInput.value = '';
                    document.getElementById('send-btn').disabled = true;
                    // 消息会通过WebSocket回显，不需要手动添加
                } else {
                    alert('发送失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('发送消息失败:', error);
                alert('发送失败，请重试');
            });
        }
    }

    function addMessage(messageData) {
        const chatMessages = document.getElementById('chat-messages');
        if (!chatMessages) return;

        // 检查消息是否已存在
        const existingMessage = chatMessages.querySelector(`[data-message-id="${messageData.id}"]`);
        if (existingMessage) return;

        const currentUserId = {{ request.user.id }};
        const isSent = messageData.sender_id === currentUserId;
        const messageClass = isSent ? 'sent' : 'received';
        const time = formatMessageTime(messageData.created_at);

        const messageHtml = `
            <div class="message ${messageClass}" data-message-id="${messageData.id}">
                <div class="message-wrapper">
                    <div class="message-bubble">
                        ${escapeHtml(messageData.content)}
                    </div>
                    <div class="message-time">${time}</div>
                </div>
            </div>
        `;

        chatMessages.insertAdjacentHTML('beforeend', messageHtml);
        chatMessages.scrollTop = chatMessages.scrollHeight;
    }


    // 加载好友列表
    window.loadFriendsList = function() {
        fetch('/social/friends/list/')
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    displayFriendsList(data.friends);
                }
            })
            .catch(error => console.error('加载好友列表失败:', error));

        // 同时加载好友请求数量
        loadFriendRequestsCount();
    };

    // 加载好友请求数量
    function loadFriendRequestsCount() {
        fetch('/social/friends/requests/')
            .then(res => res.json())
            .then(data => {
                if (data.success && data.received.length > 0) {
                    const badge = document.getElementById('friend-request-badge');
                    badge.textContent = data.received.length;
                    badge.style.display = 'inline-block';
                } else {
                    document.getElementById('friend-request-badge').style.display = 'none';
                }
            })
            .catch(error => console.error('加载好友请求数量失败:', error));
    }

    // 显示好友列表
    function displayFriendsList(friends) {
        const friendsList = document.getElementById('friends-list');
        if (friends.length === 0) {
            friendsList.innerHTML = '<div class="empty-conversations"><i class="fas fa-user-friends"></i><p>暂无好友</p></div>';
            return;
        }

        friendsList.innerHTML = friends.map(friend => `
            <div class="friend-item" onclick="viewFriendProfile(${friend.id})" style="cursor: pointer;">
                <img src="${friend.avatar || '/static/imgs/default-avatar.jpg'}"
                     alt="${friend.nickname}"
                     class="friend-avatar">
                <div class="friend-info">
                    <div class="friend-name">${friend.nickname}</div>
                    <div class="friend-status">@${friend.username}</div>
                </div>
                <div class="friend-actions" onclick="event.stopPropagation();">
                    <button class="friend-action-btn primary" onclick="startConversationWithFriend(${friend.id}, ${friend.conversation_id || 'null'})">
                        发消息
                    </button>
                </div>
            </div>
        `).join('');
    }

    // 查看好友主页
    function viewFriendProfile(friendId) {
        window.location.href = `/social/friends/profile/${friendId}/`;
    }

    // 加载群组列表
    window.loadGroupsList = function() {
        fetch('/social/groups/list/')
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    displayGroupsList(data.groups);
                }
            })
            .catch(error => console.error('加载群组列表失败:', error));
    };

    // 显示群组列表
    function displayGroupsList(groups) {
        const groupsList = document.getElementById('groups-list');
        if (groups.length === 0) {
            groupsList.innerHTML = '<div class="empty-conversations"><i class="fas fa-users"></i><p>暂无群组</p></div>';
            return;
        }

        groupsList.innerHTML = groups.map(group => `
            <div class="group-item" onclick="openGroupChat(${group.id})">
                <img src="${group.avatar || '/static/imgs/default-group-avatar.jpeg'}"
                     alt="${group.name}"
                     class="group-avatar"
                     onerror="this.src='/static/imgs/default-group-avatar.jpeg'">
                <div class="group-info">
                    <div class="group-name">${group.name}</div>
                    <div class="group-members">${group.member_count} 人</div>
                </div>
            </div>
        `).join('');
    }
});

// 模态框控制函数（在DOMContentLoaded外部）
function showSearchFriendModal() {
    document.getElementById('searchFriendModal').classList.add('active');
    document.getElementById('friend-search-input').focus();
}

function closeSearchFriendModal() {
    document.getElementById('searchFriendModal').classList.remove('active');
    document.getElementById('friend-search-results').innerHTML = '';
    document.getElementById('friend-search-input').value = '';
}

// 显示好友请求模态框
function showFriendRequestsModal() {
    document.getElementById('friendRequestsModal').classList.add('active');
    loadFriendRequests();
}

function closeFriendRequestsModal() {
    document.getElementById('friendRequestsModal').classList.remove('active');
}

// 加载好友请求
function loadFriendRequests() {
    fetch('/social/friends/requests/')
        .then(res => res.json())
        .then(data => {
            if (data.success) {
                displayFriendRequests(data.received, data.sent);
            }
        })
        .catch(error => console.error('加载好友请求失败:', error));
}

// 显示好友请求
function displayFriendRequests(received, sent) {
    const receivedContainer = document.getElementById('received-requests');
    const sentContainer = document.getElementById('sent-requests');

    // 显示收到的请求
    if (received.length === 0) {
        receivedContainer.innerHTML = '<p style="text-align: center; color: #999; padding: 20px;">暂无收到的请求</p>';
    } else {
        receivedContainer.innerHTML = received.map(req => {
            const time = new Date(req.created_at).toLocaleString('zh-CN', {
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit'
            });
            return `
                <div class="request-item">
                    <img src="${req.user.avatar || '/static/imgs/default-avatar.jpg'}"
                         alt="${req.user.nickname}"
                         class="request-avatar">
                    <div class="request-info">
                        <div class="request-name">${req.user.nickname}</div>
                        <div class="request-time">${time}</div>
                    </div>
                    <div class="request-actions">
                        <button class="request-btn accept" onclick="acceptFriendRequest(${req.id})">
                            <i class="fas fa-check"></i> 接受
                        </button>
                        <button class="request-btn reject" onclick="rejectFriendRequest(${req.id})">
                            <i class="fas fa-times"></i> 拒绝
                        </button>
                    </div>
                </div>
            `;
        }).join('');
    }

    // 显示发送的请求
    if (sent.length === 0) {
        sentContainer.innerHTML = '<p style="text-align: center; color: #999; padding: 20px;">暂无发送的请求</p>';
    } else {
        sentContainer.innerHTML = sent.map(req => {
            const time = new Date(req.created_at).toLocaleString('zh-CN', {
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit'
            });
            return `
                <div class="request-item">
                    <img src="${req.user.avatar || '/static/imgs/default-avatar.jpg'}"
                         alt="${req.user.nickname}"
                         class="request-avatar">
                    <div class="request-info">
                        <div class="request-name">${req.user.nickname}</div>
                        <div class="request-time">${time}</div>
                    </div>
                    <div class="request-actions">
                        <span style="color: #999; font-size: 13px;">等待对方确认</span>
                    </div>
                </div>
            `;
        }).join('');
    }
}

// 接受好友请求
function acceptFriendRequest(requestId) {
    fetch(`/social/friends/request/accept/${requestId}/`, {
        method: 'POST',
        headers: {
            'X-CSRFToken': getCookie('csrftoken')
        }
    })
    .then(res => res.json())
    .then(data => {
        if (data.success) {
            alert(data.message);
            loadFriendRequests();
            loadFriendRequestsCount();
            loadFriendsList(); // 刷新好友列表
        } else {
            alert(data.message);
        }
    })
    .catch(error => {
        console.error('接受好友请求失败:', error);
    });
}

// 拒绝好友请求
function rejectFriendRequest(requestId) {
    if (!confirm('确定要拒绝这个好友请求吗？')) {
        return;
    }

    fetch(`/social/friends/request/reject/${requestId}/`, {
        method: 'POST',
        headers: {
            'X-CSRFToken': getCookie('csrftoken')
        }
    })
    .then(res => res.json())
    .then(data => {
        if (data.success) {
            alert(data.message);
            loadFriendRequests();
            loadFriendRequestsCount();
        } else {
            alert(data.message);
        }
    })
    .catch(error => {
        console.error('拒绝好友请求失败:', error);
    });
}

function showCreateGroupModal() {
    document.getElementById('createGroupModal').classList.add('active');
    selectedGroupMembers = [];
    loadFriendsForGroup();
}

function closeCreateGroupModal() {
    document.getElementById('createGroupModal').classList.remove('active');
    document.getElementById('group-name-input').value = '';
    document.getElementById('group-description-input').value = '';
    document.getElementById('group-member-search').value = '';
    selectedGroupMembers = [];
}

// 搜索用户
document.addEventListener('DOMContentLoaded', function() {
    const friendSearchInput = document.getElementById('friend-search-input');
    if (friendSearchInput) {
        let searchTimeout;
        friendSearchInput.addEventListener('input', function(e) {
            clearTimeout(searchTimeout);
            const query = e.target.value.trim();

            if (query.length < 2) {
                document.getElementById('friend-search-results').innerHTML = '';
                return;
            }

            searchTimeout = setTimeout(() => {
                fetch(`/social/friends/search/?q=${encodeURIComponent(query)}`)
                    .then(res => res.json())
                    .then(data => {
                        if (data.success) {
                            displaySearchResults(data.users);
                        }
                    })
                    .catch(error => console.error('搜索失败:', error));
            }, 300);
        });
    }
});

// 显示搜索结果
function displaySearchResults(users) {
    const resultsContainer = document.getElementById('friend-search-results');

    if (users.length === 0) {
        resultsContainer.innerHTML = '<p style="text-align: center; color: #999; padding: 20px;">未找到用户</p>';
        return;
    }

    resultsContainer.innerHTML = users.map(user => {
        let actionBtn = '';
        if (user.is_friend) {
            actionBtn = '<span style="color: #999; font-size: 12px;">已是好友</span>';
        } else if (user.pending_status === 'sent') {
            actionBtn = '<span style="color: #999; font-size: 12px;">已发送请求</span>';
        } else if (user.pending_status === 'received') {
            actionBtn = '<button class="friend-action-btn primary" onclick="acceptFriendRequest(' + user.id + ')">接受请求</button>';
        } else {
            actionBtn = '<button class="friend-action-btn primary" onclick="sendFriendRequest(' + user.id + ')">添加好友</button>';
        }

        return `
            <div class="search-result-item">
                <img src="${user.avatar || '/static/imgs/default-avatar.jpg'}"
                     alt="${user.nickname}"
                     class="search-result-avatar">
                <div class="search-result-info">
                    <div class="search-result-name">${user.nickname}</div>
                    <div class="search-result-username">@${user.username}</div>
                </div>
                ${actionBtn}
            </div>
        `;
    }).join('');
}

// 发送好友请求
function sendFriendRequest(userId) {
    fetch(`/social/friends/request/send/${userId}/`, {
        method: 'POST',
        headers: {
            'X-CSRFToken': getCookie('csrftoken')
        }
    })
    .then(res => res.json())
    .then(data => {
        alert(data.message);
        if (data.success) {
            // 重新搜索以更新状态
            const searchInput = document.getElementById('friend-search-input');
            if (searchInput.value) {
                searchInput.dispatchEvent(new Event('input'));
            }
        }
    })
    .catch(error => {
        console.error('发送好友请求失败:', error);
        alert('操作失败，请重试');
    });
}

// 加载好友列表用于创建群组
function loadFriendsForGroup() {
    fetch('/social/friends/list/')
        .then(res => res.json())
        .then(data => {
            if (data.success) {
                displayFriendsForGroup(data.friends);
            }
        })
        .catch(error => console.error('加载好友列表失败:', error));
}

// 显示可添加到群组的好友
function displayFriendsForGroup(friends) {
    const resultsContainer = document.getElementById('group-member-results');

    if (friends.length === 0) {
        resultsContainer.innerHTML = '<p style="text-align: center; color: #999; padding: 20px;">暂无好友</p>';
        return;
    }

    resultsContainer.innerHTML = friends.map(friend => `
        <div class="search-result-item" onclick="toggleGroupMember(${friend.id}, '${friend.nickname}', '${friend.avatar || '/static/imgs/default-avatar.jpg'}', event)">
            <img src="${friend.avatar || '/static/imgs/default-avatar.jpg'}"
                 alt="${friend.nickname}"
                 class="search-result-avatar">
            <div class="search-result-info">
                <div class="search-result-name">${friend.nickname}</div>
                <div class="search-result-username">@${friend.username}</div>
            </div>
            <input type="checkbox" id="member-${friend.id}" ${selectedGroupMembers.includes(friend.id) ? 'checked' : ''} onclick="toggleGroupMember(${friend.id}, '${friend.nickname}', '${friend.avatar || '/static/imgs/default-avatar.jpg'}', event)">
        </div>
    `).join('');
}

// 切换群组成员选择
function toggleGroupMember(userId, nickname, avatar, event) {
    // 如果点击的是checkbox本身，不需要再次切换
    const checkbox = document.getElementById(`member-${userId}`);
    if (event && event.target === checkbox) {
        // checkbox已经被切换了，只需要更新selectedGroupMembers
        if (checkbox.checked) {
            if (!selectedGroupMembers.includes(userId)) {
                selectedGroupMembers.push(userId);
            }
        } else {
            selectedGroupMembers = selectedGroupMembers.filter(id => id !== userId);
        }
    } else {
        // 点击的是div，需要手动切换checkbox
        checkbox.checked = !checkbox.checked;

        if (checkbox.checked) {
            if (!selectedGroupMembers.includes(userId)) {
                selectedGroupMembers.push(userId);
            }
        } else {
            selectedGroupMembers = selectedGroupMembers.filter(id => id !== userId);
        }
    }

    updateSelectedMembers();
}

// 更新已选择的成员显示
function updateSelectedMembers() {
    const container = document.getElementById('selected-members');
    if (selectedGroupMembers.length === 0) {
        container.innerHTML = '';
        return;
    }

    container.innerHTML = `<p style="font-size: 13px; color: #666; margin-bottom: 5px;">已选择 ${selectedGroupMembers.length} 人</p>`;
}

// 创建群组
function createGroup() {
    const name = document.getElementById('group-name-input').value.trim();
    const description = document.getElementById('group-description-input').value.trim();

    if (!name) {
        alert('请输入群组名称');
        return;
    }

    fetch('/social/groups/create/', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': getCookie('csrftoken')
        },
        body: JSON.stringify({
            name: name,
            description: description,
            member_ids: selectedGroupMembers
        })
    })
    .then(res => res.json())
    .then(data => {
        alert(data.message);
        if (data.success) {
            closeCreateGroupModal();
            // 切换到群组标签页并刷新列表
            document.querySelector('[data-tab="groups"]').click();
        }
    })
    .catch(error => {
        console.error('创建群组失败:', error);
        alert('创建失败，请重试');
    });
}

// 开始与好友对话
function startConversationWithFriend(friendId, conversationId) {
    if (conversationId) {
        // 如果已有会话，直接打开
        openConversation(conversationId);
    } else {
        // 创建新会话
        fetch(`/social/conversations/start/${friendId}/`, {
            method: 'POST',
            headers: {
                'X-CSRFToken': getCookie('csrftoken')
            }
        })
        .then(res => res.json())
        .then(data => {
            if (data.success) {
                // 刷新会话列表并打开新会话
                location.reload();
            } else {
                alert(data.message || '创建会话失败');
            }
        })
        .catch(error => {
            console.error('创建会话失败:', error);
            alert('操作失败，请重试');
        });
    }
}

// 打开已有会话
function openConversation(conversationId) {
    // 切换到消息标签页
    document.querySelector('[data-tab="conversations"]').click();

    // 触发点击对应的会话项
    setTimeout(() => {
        const conversationItem = document.querySelector(`[data-conversation-id="${conversationId}"]`);
        if (conversationItem) {
            conversationItem.click();
        }
    }, 100);
}

// 打开群组聊天
function openGroupChat(groupId) {
    currentGroupId = groupId;
    currentConversationId = null;
    currentChatType = 'group';

    // 关闭之前的WebSocket连接
    if (chatSocket) {
        chatSocket.close();
    }

    // 加载群组聊天界面
    fetch(`/social/groups/${groupId}/`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                renderGroupChatArea(data.group);
                connectGroupWebSocket(groupId);
                loadGroupMessages(groupId);
            } else {
                alert(data.message);
            }
        })
        .catch(error => {
            console.error('加载群组失败:', error);
            alert('加载群组失败，请重试');
        });
}

// 渲染群组聊天区域
function renderGroupChatArea(group) {
    const chatArea = document.getElementById('chat-area');
    chatArea.classList.remove('empty');

    const isOwner = group.user_role === 'owner';

    chatArea.innerHTML = `
        <div class="chat-header">
            <div class="chat-header-left">
                <img src="${group.avatar || '/static/imgs/default-group-avatar.jpeg'}"
                     alt="${group.name}"
                     class="chat-header-avatar"
                     onerror="this.src='/static/imgs/default-group-avatar.jpeg'">
                <div class="chat-header-info">
                    <h3>${group.name}</h3>
                    <p>${group.member_count} 成员</p>
                </div>
            </div>
            <div class="chat-header-actions">
                <button class="group-action-btn btn-invite-member" onclick="showInviteMemberModal(${group.id})">
                    <i class="fas fa-user-plus"></i>
                    <span>邀请成员</span>
                </button>
                ${isOwner ? `
                <button class="group-action-btn btn-member-settings" onclick="showGroupMembersModal(${group.id})">
                    <i class="fas fa-users-cog"></i>
                    <span>成员设置</span>
                </button>
                <button class="group-action-btn btn-group-settings" onclick="showGroupSettingsModal(${group.id})">
                    <i class="fas fa-cog"></i>
                    <span>群组设置</span>
                </button>
                ` : ''}
            </div>
        </div>
        
        <div class="chat-messages" id="chat-messages">
            <div style="text-align: center; color: #999; padding: 40px;">加载中...</div>
        </div>
        
        <div class="chat-input-container">
            <input type="text" 
                   class="chat-input" 
                   id="message-input" 
                   placeholder="输入消息..." 
                   maxlength="1000">
            <button class="send-btn" id="send-btn" disabled>
                <i class="fas fa-paper-plane"></i>
            </button>
        </div>
    `;
    
    // 绑定输入框和发送按钮事件
    const messageInput = document.getElementById('message-input');
    const sendBtn = document.getElementById('send-btn');
    
    messageInput.addEventListener('input', function() {
        sendBtn.disabled = !this.value.trim();
    });
    
    messageInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter' && !e.shiftKey && this.value.trim()) {
            e.preventDefault();
            sendGroupMessage();
        }
    });
    
    sendBtn.addEventListener('click', sendGroupMessage);
}

// 加载群组消息
function loadGroupMessages(groupId) {
    fetch(`/social/groups/${groupId}/messages/`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const chatMessages = document.getElementById('chat-messages');
                if (data.messages.length === 0) {
                    chatMessages.innerHTML = '<div style="text-align: center; color: #999; padding: 40px;">暂无消息</div>';
                } else {
                    chatMessages.innerHTML = renderGroupMessages(data.messages);
                    chatMessages.scrollTop = chatMessages.scrollHeight;
                }
            }
        })
        .catch(error => console.error('加载群组消息失败:', error));
}

// 渲染群组消息
function renderGroupMessages(messages) {
    let currentUserId = {{ request.user.id }};
    return messages.map(msg => {
        let msgIsSent = msg.sender_id === currentUserId;
        let msgClass = msgIsSent ? 'sent' : 'received';
        let msgTime = formatMessageTime(msg.created_at);
        
        if (msg.message_type === 'system') {
            return `
                <div style="text-align: center; color: #999; padding: 10px; font-size: 12px;">
                    ${escapeHtml(msg.content)}
                </div>
            `;
        }
        
        return `
            <div class="message ${msgClass}" data-message-id="${msg.id}">
                <div class="message-wrapper">
                    ${!msgIsSent ? `<div style="font-size: 12px; color: #666; margin-bottom: 4px;">${msg.sender_nickname}</div>` : ''}
                    <div class="message-bubble">
                        ${escapeHtml(msg.content)}
                    </div>
                    <div class="message-time">${msgTime}</div>
                </div>
            </div>
        `;
    }).join('');
}

// 发送群组消息
function sendGroupMessage() {
    const messageInput = document.getElementById('message-input');
    const content = messageInput.value.trim();
    
    if (!content || !currentGroupId) return;
    
    if (chatSocket && chatSocket.readyState === WebSocket.OPEN) {
        // 通过WebSocket发送
        chatSocket.send(JSON.stringify({
            type: 'group_message',
            message: content
        }));
        messageInput.value = '';
        document.getElementById('send-btn').disabled = true;
    } else {
        // 降级到HTTP API
        fetch(`/social/groups/${currentGroupId}/send/`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCookie('csrftoken')
            },
            body: JSON.stringify({ content: content })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                messageInput.value = '';
                document.getElementById('send-btn').disabled = true;
                loadGroupMessages(currentGroupId);
            } else {
                alert('发送失败: ' + data.message);
            }
        })
        .catch(error => {
            console.error('发送消息失败:', error);
            alert('发送失败，请重试');
        });
    }
}

// 连接群组WebSocket
function connectGroupWebSocket(groupId) {
    const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
    const wsUrl = `${protocol}//${window.location.host}/ws/group/${groupId}/`;
    
    chatSocket = new WebSocket(wsUrl);
    
    chatSocket.onopen = function(e) {
        console.log('群组WebSocket连接已建立');
    };
    
    chatSocket.onmessage = function(e) {
        const data = JSON.parse(e.data);
        
        if (data.type === 'group_message') {
            addGroupMessage(data.message);
        } else if (data.type === 'group_update') {
            handleGroupUpdate(data.update);
        }
    };
    
    chatSocket.onclose = function(e) {
        console.log('群组WebSocket连接已关闭');
    };
    
    chatSocket.onerror = function(e) {
        console.error('群组WebSocket错误:', e);
    };
}

// 添加群组消息
function addGroupMessage(messageData) {
    let chatMessages = document.getElementById('chat-messages');
    if (!chatMessages) return;
    
    // 检查消息是否已存在
    let existingMessage = chatMessages.querySelector(`[data-message-id="${messageData.id}"]`);
    if (existingMessage) return;
    
    let currentUserId = {{ request.user.id }};
    let grpIsSent = messageData.sender_id === currentUserId;
    let grpMsgClass = grpIsSent ? 'sent' : 'received';
    let grpTime = formatMessageTime(messageData.created_at);
    
    let grpMsgHtml = `
        <div class="message ${grpMsgClass}" data-message-id="${messageData.id}">
            <div class="message-wrapper">
                ${!grpIsSent ? `<div style="font-size: 12px; color: #666; margin-bottom: 4px;">${messageData.sender.nickname}</div>` : ''}
                <div class="message-bubble">
                    ${escapeHtml(messageData.content)}
                </div>
                <div class="message-time">${grpTime}</div>
            </div>
        </div>
    `;
    
    chatMessages.insertAdjacentHTML('beforeend', grpMsgHtml);
    chatMessages.scrollTop = chatMessages.scrollHeight;
    
    // 刷新群组列表
    if (document.querySelector('[data-tab="groups"].active')) {
        loadGroupsList();
    }
}

// 处理群组更新
function handleGroupUpdate(update) {
    if (update.type === 'info_updated') {
        // 更新群组信息显示
        const headerInfo = document.querySelector('.chat-header-info h3');
        if (headerInfo && update.group) {
            headerInfo.textContent = update.group.name;
        }
        alert('群组信息已更新');
    } else if (update.type === 'avatar_updated') {
        // 更新群组头像
        const headerAvatar = document.querySelector('.chat-header-avatar');
        if (headerAvatar && update.group) {
            headerAvatar.src = update.group.avatar;
        }
        alert('群组头像已更新');
    } else if (update.type === 'member_added') {
        // 有新成员加入
        if (currentGroupId) {
            // 刷新群组信息以更新成员数
            loadGroupMessages(currentGroupId);
        }
    } else if (update.type === 'member_removed') {
        // 有成员被移除
        if (currentGroupId) {
            // 刷新群组信息以更新成员数
            loadGroupMessages(currentGroupId);
        }
    }
    
    // 刷新群组列表
    loadGroupsList();
}

// 自动刷新功能
let autoRefreshInterval = null;

function startAutoRefresh() {
    // 每30秒自动刷新一次
    autoRefreshInterval = setInterval(() => {
        // 获取当前激活的标签
        const activeTab = document.querySelector('.tab-btn.active');
        if (!activeTab) return;

        const tabName = activeTab.getAttribute('data-tab');

        // 根据当前标签刷新对应内容
        if (tabName === 'conversations') {
            // 刷新会话列表（重新加载页面的会话数据）
            refreshConversations();
        } else if (tabName === 'friends') {
            loadFriendsList();
            loadFriendRequestsCount();
        } else if (tabName === 'groups') {
            loadGroupsList();
        }
    }, 30000); // 30秒
}

function stopAutoRefresh() {
    if (autoRefreshInterval) {
        clearInterval(autoRefreshInterval);
        autoRefreshInterval = null;
    }
}

// 刷新会话列表
function refreshConversations() {
    // 简单实现：重新加载页面
    // 更好的实现应该是通过AJAX获取新数据并更新DOM
    fetch('/social/chat/conversations/list/')
        .then(res => res.json())
        .then(data => {
            if (data.success) {
                // 更新会话列表
                updateConversationsList(data.conversations);
            }
        })
        .catch(error => console.error('刷新会话列表失败:', error));
}

function updateConversationsList(conversations) {
    const conversationsList = document.getElementById('conversations-tab');
    if (!conversationsList) return;
    
    if (conversations.length === 0) {
        conversationsList.innerHTML = `
            <div class="empty-conversations">
                <i class="fas fa-comments"></i>
                <p>暂无对话</p>
                <p style="font-size: 12px; margin-top: 8px;">
                    <a href="{% url 'social:user_list' %}" style="color: #667eea;">开始新对话</a>
                </p>
            </div>
        `;
        return;
    }
    
    conversationsList.innerHTML = conversations.map(conv => `
        <div class="conversation-item" 
             data-conversation-id="${conv.conversation_id}"
             data-user-id="${conv.other_user.id}"
             data-user-name="${conv.other_user.nickname}">
            <img src="${conv.other_user.avatar || '/static/imgs/default-avatar.jpg'}"
                 alt="${conv.other_user.nickname}" 
                 class="conversation-avatar">
            <div class="conversation-info">
                <div class="conversation-name">${conv.other_user.nickname}</div>
                <div class="conversation-preview">${conv.last_message ? conv.last_message.content : '开始对话...'}</div>
            </div>
            <div class="conversation-meta">
                ${conv.last_message ? `<div class="conversation-time">${formatTime(conv.last_message.created_at)}</div>` : ''}
                ${conv.unread_count > 0 ? `<span class="unread-badge">${conv.unread_count}</span>` : ''}
            </div>
        </div>
    `).join('');
    
    // 重新绑定点击事件
    document.querySelectorAll('.conversation-item').forEach(item => {
        item.addEventListener('click', function() {
            const conversationId = this.getAttribute('data-conversation-id');
            const userId = this.getAttribute('data-user-id');
            
            document.querySelectorAll('.conversation-item').forEach(i => i.classList.remove('active'));
            this.classList.add('active');
            
            // 这里需要调用loadChat函数，但它在DOMContentLoaded作用域内
            // 简单处理：刷新页面
            window.location.href = `/social/chat/?conversation=${conversationId}`;
        });
    });
}

function formatTime(isoString) {
    const date = new Date(isoString);
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    return `${month}-${day} ${hours}:${minutes}`;
}

// 页面加载时启动自动刷新
document.addEventListener('DOMContentLoaded', function() {
    startAutoRefresh();
});

// 页面卸载时停止自动刷新
window.addEventListener('beforeunload', function() {
    stopAutoRefresh();
});

// 显示邀请成员模态框
function showInviteMemberModal(groupId) {
    // 获取好友列表
    fetch('/social/friends/list/')
        .then(res => res.json())
        .then(data => {
            if (data.success) {
                const friends = data.friends;
                const modalHtml = `
                    <div class="modal active" id="inviteMemberModal">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h3>邀请好友加入群组</h3>
                                <button class="modal-close" onclick="closeInviteMemberModal()">&times;</button>
                            </div>
                            <div class="form-group">
                                <input type="text" id="search-invite-friend" placeholder="搜索好友..." style="width: 100%; padding: 8px; margin-bottom: 10px;">
                            </div>
                            <div id="invite-friends-list" style="max-height: 400px; overflow-y: auto;">
                                ${friends.map(friend => `
                                    <div class="friend-item" style="padding: 10px; border-bottom: 1px solid #eee;">
                                        <img src="${friend.avatar || '/static/imgs/default-avatar.jpg'}"
                                             alt="${friend.nickname}" 
                                             style="width: 40px; height: 40px; border-radius: 50%; margin-right: 10px;">
                                        <div style="flex: 1;">
                                            <div style="font-weight: 500;">${friend.nickname}</div>
                                            <div style="font-size: 12px; color: #666;">@${friend.username}</div>
                                        </div>
                                        <button class="friend-action-btn primary" onclick="inviteMemberToGroup(${groupId}, ${friend.id}, '${friend.nickname}')">
                                            <i class="fas fa-plus"></i> 邀请
                                        </button>
                                    </div>
                                `).join('')}
                            </div>
                        </div>
                    </div>
                `;
                document.body.insertAdjacentHTML('beforeend', modalHtml);
                
                // 添加搜索功能
                document.getElementById('search-invite-friend').addEventListener('input', function(e) {
                    const searchTerm = e.target.value.toLowerCase();
                    const friendItems = document.querySelectorAll('#invite-friends-list .friend-item');
                    friendItems.forEach(item => {
                        const text = item.textContent.toLowerCase();
                        item.style.display = text.includes(searchTerm) ? 'flex' : 'none';
                    });
                });
            }
        })
        .catch(error => console.error('获取好友列表失败:', error));
}

function closeInviteMemberModal() {
    const modal = document.getElementById('inviteMemberModal');
    if (modal) {
        modal.remove();
    }
}

// 邀请成员加入群组
function inviteMemberToGroup(groupId, userId, userName) {
    fetch(`/social/groups/${groupId}/members/add/`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': getCookie('csrftoken')
        },
        body: JSON.stringify({ user_id: userId })
    })
    .then(res => res.json())
    .then(data => {
        if (data.success) {
            alert(`已成功邀请 ${userName} 加入群组`);
            closeInviteMemberModal();
            // 刷新群组信息
            if (currentGroupId === groupId) {
                openGroupChat(groupId);
            }
        } else {
            alert(data.message);
        }
    })
    .catch(error => {
        console.error('邀请成员失败:', error);
        alert('操作失败，请重试');
    });
}

// 显示群组成员管理模态框（仅群主）
function showGroupMembersModal(groupId) {
    fetch(`/social/groups/${groupId}/`)
        .then(res => res.json())
        .then(data => {
            if (data.success) {
                const group = data.group;
                const members = group.members || [];
                
                const modalHtml = `
                    <div class="modal active" id="groupMembersModal">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h3>成员管理</h3>
                                <button class="modal-close" onclick="closeGroupMembersModal()">&times;</button>
                            </div>
                            <div id="group-members-list" style="max-height: 400px; overflow-y: auto;">
                                ${members.map(member => `
                                    <div class="friend-item" style="padding: 10px; border-bottom: 1px solid #eee;">
                                        <img src="${member.avatar || '/static/imgs/default-avatar.jpg'}"
                                             alt="${member.nickname}" 
                                             style="width: 40px; height: 40px; border-radius: 50%; margin-right: 10px;">
                                        <div style="flex: 1;">
                                            <div style="font-weight: 500;">
                                                ${member.nickname}
                                                ${member.role === 'owner' ? '<span style="color: #667eea; font-size: 12px;">(群主)</span>' : ''}
                                                ${member.role === 'admin' ? '<span style="color: #f59e0b; font-size: 12px;">(管理员)</span>' : ''}
                                            </div>
                                            <div style="font-size: 12px; color: #666;">@${member.username}</div>
                                        </div>
                                        ${member.role !== 'owner' ? `
                                            <button class="friend-action-btn" style="color: #dc3545; border-color: #dc3545;" 
                                                    onclick="removeMemberFromGroup(${groupId}, ${member.id}, '${member.nickname}')">
                                                <i class="fas fa-user-times"></i> 踢出
                                            </button>
                                        ` : ''}
                                    </div>
                                `).join('')}
                            </div>
                            <div style="margin-top: 20px; padding-top: 20px; border-top: 1px solid #e0e0e0;">
                                <button class="submit-btn" style="background: #ff4757; width: 100%;" onclick="dissolveGroup(${groupId}, '${group.name}')">
                                    <i class="fas fa-trash-alt"></i> 解散群聊
                                </button>
                                <p style="text-align: center; color: #999; font-size: 12px; margin-top: 10px;">
                                    解散群聊后，所有成员将被移除，群聊记录将被删除
                                </p>
                            </div>
                        </div>
                    </div>
                `;
                document.body.insertAdjacentHTML('beforeend', modalHtml);
            }
        })
        .catch(error => console.error('获取群组成员失败:', error));
}

function closeGroupMembersModal() {
    const modal = document.getElementById('groupMembersModal');
    if (modal) {
        modal.remove();
    }
}

// 踢出群组成员（仅群主）
function removeMemberFromGroup(groupId, userId, userName) {
    if (!confirm(`确定要将 ${userName} 踢出群组吗？`)) {
        return;
    }
    
    fetch(`/social/groups/${groupId}/members/remove/${userId}/`, {
        method: 'POST',
        headers: {
            'X-CSRFToken': getCookie('csrftoken')
        }
    })
    .then(res => res.json())
    .then(data => {
        if (data.success) {
            alert(data.message);
            closeGroupMembersModal();
            // 刷新群组信息
            if (currentGroupId === groupId) {
                openGroupChat(groupId);
            }
        } else {
            alert(data.message);
        }
    })
    .catch(error => {
        console.error('踢出成员失败:', error);
        alert('操作失败，请重试');
    });
}

// 显示群组设置模态框
function showGroupSettingsModal(groupId) {
    // 获取群组信息
    fetch(`/social/groups/${groupId}/`)
        .then(res => res.json())
        .then(data => {
            if (data.success) {
                const group = data.group;
                const modalHtml = `
                    <div class="modal active" id="groupSettingsModal">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h3>群组设置</h3>
                                <button class="modal-close" onclick="closeGroupSettingsModal()">&times;</button>
                            </div>
                            <div class="form-group">
                                <label>群组名称</label>
                                <input type="text" id="edit-group-name" value="${group.name}">
                            </div>
                            <div class="form-group">
                                <label>群组描述</label>
                                <textarea id="edit-group-description">${group.description || ''}</textarea>
                            </div>
                            <div class="form-group">
                                <label>群组头像</label>
                                <input type="file" id="edit-group-avatar" accept="image/*">
                            </div>
                            <button class="submit-btn" onclick="updateGroupInfo(${groupId})">保存修改</button>
                        </div>
                    </div>
                `;
                document.body.insertAdjacentHTML('beforeend', modalHtml);
            }
        })
        .catch(error => console.error('获取群组信息失败:', error));
}

function closeGroupSettingsModal() {
    const modal = document.getElementById('groupSettingsModal');
    if (modal) {
        modal.remove();
    }
}

// 更新群组信息
function updateGroupInfo(groupId) {
    const name = document.getElementById('edit-group-name').value.trim();
    const description = document.getElementById('edit-group-description').value.trim();
    const avatarFile = document.getElementById('edit-group-avatar').files[0];
    
    if (!name) {
        alert('请输入群组名称');
        return;
    }
    
    // 更新基本信息
    fetch(`/social/groups/${groupId}/update/`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': getCookie('csrftoken')
        },
        body: JSON.stringify({
            name: name,
            description: description
        })
    })
    .then(res => res.json())
    .then(data => {
        if (data.success) {
            // 如果有头像文件，上传头像
            if (avatarFile) {
                const formData = new FormData();
                formData.append('avatar', avatarFile);
                
                return fetch(`/social/groups/${groupId}/avatar/`, {
                    method: 'POST',
                    headers: {
                        'X-CSRFToken': getCookie('csrftoken')
                    },
                    body: formData
                }).then(res => res.json());
            }
            return data;
        } else {
            throw new Error(data.message);
        }
    })
    .then(data => {
        alert('群组信息已更新');
        closeGroupSettingsModal();
        // 刷新群组列表和当前聊天界面
        loadGroupsList();
        if (currentGroupId === groupId) {
            openGroupChat(groupId);
        }
    })
    .catch(error => {
        console.error('更新群组信息失败:', error);
        alert('更新失败: ' + error.message);
    });
}

// 加载系统通知
function loadSystemNotifications() {
    console.log('Loading system notifications...');

    fetch('/social/notifications/list/')
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(data => {
            console.log('Notifications data:', data);
            if (data.success) {
                displayNotificationsList(data.notifications);
            } else {
                console.error('获取通知失败:', data.message);
                document.getElementById('notifications-list').innerHTML =
                    '<div class="empty-conversations"><i class="fas fa-bell"></i><p>加载通知失败</p></div>';
            }
        })
        .catch(error => {
            console.error('获取通知请求失败:', error);
            document.getElementById('notifications-list').innerHTML =
                '<div class="empty-conversations"><i class="fas fa-bell"></i><p>加载失败，请刷新页面</p></div>';
        });
}

// 显示通知列表（左侧简略信息）
function displayNotificationsList(notifications) {
    const notificationsList = document.getElementById('notifications-list');

    if (!notificationsList) {
        console.error('找不到通知列表容器');
        return;
    }

    notificationsList.innerHTML = '';

    if (!notifications || notifications.length === 0) {
        notificationsList.innerHTML = '<div class="empty-conversations"><i class="fas fa-bell"></i><p>暂无系统通知</p></div>';
        return;
    }

    notifications.forEach(notification => {
        const notificationElement = document.createElement('div');
        notificationElement.className = `conversation-item ${notification.is_read ? '' : 'unread'}`;
        notificationElement.setAttribute('data-notification-id', notification.id);

        // 简略信息：只显示标题和活动名称（如果有关联活动）
        let previewText = notification.title;
        if (notification.related_activity) {
            previewText = `活动: ${notification.related_activity.title}`;
        }

        // 格式化时间
        const notificationTime = new Date(notification.created_at).toLocaleString('zh-CN', {
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit'
        });

        notificationElement.innerHTML = `
            <div class="conversation-info">
                <div class="conversation-name">${escapeHtml(notification.title)}</div>
                <div class="conversation-preview">${escapeHtml(previewText)}</div>
            </div>
            <div class="conversation-meta">
                <div class="conversation-time">${notificationTime}</div>
                ${!notification.is_read ? '<span class="unread-badge">新</span>' : ''}
            </div>
        `;

        // 添加点击事件
        notificationElement.addEventListener('click', function() {
            showNotificationDetail(notification);
            // 标记为已读
            if (!notification.is_read) {
                markNotificationAsRead(notification.id, this);
            }
        });

        notificationsList.appendChild(notificationElement);
    });
}

// 显示通知详情（右侧完整信息）
function showNotificationDetail(notification) {
    const chatArea = document.getElementById('chat-area');
    chatArea.classList.remove('empty');

    // 格式化时间
    const notificationTime = new Date(notification.created_at).toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
    });

    // 构建详细内容
    let detailContent = `
        <div class="notification-detail-content">
            <h3>${escapeHtml(notification.title)}</h3>
            <div class="notification-time">${notificationTime}</div>
            <div class="notification-message">
                ${escapeHtml(notification.content)}
            </div>
    `;

    // 添加相关活动信息
    if (notification.related_activity) {
        detailContent += `
            <div class="notification-activity">
                <h4>相关活动信息</h4>
                <div class="activity-info">
                    <p><strong>活动标题：</strong>${escapeHtml(notification.related_activity.title)}</p>
                    <p><strong>活动状态：</strong>${escapeHtml(notification.related_activity.status || '未知')}</p>
                    ${notification.related_activity.reason ? `<p><strong>审核意见：</strong>${escapeHtml(notification.related_activity.reason)}</p>` : ''}
                    ${notification.related_activity.description ? `<p><strong>活动描述：</strong>${escapeHtml(notification.related_activity.description)}</p>` : ''}
                </div>
            </div>
        `;
    }

    // 添加管理员信息（如果有）
    if (notification.admin_user) {
        detailContent += `
            <div class="notification-admin">
                <p><strong>操作管理员：</strong>${escapeHtml(notification.admin_user)}</p>
            </div>
        `;
    }

    detailContent += `</div>`;

    chatArea.innerHTML = `
        <div class="chat-header">
            <div class="chat-header-left">
                <div class="chat-header-info">
                    <h3>系统通知详情</h3>
                    <p>${notification.is_read ? '已读' : '未读'}</p>
                </div>
            </div>
            <div class="notification-actions">
                <button class="friend-action-btn" onclick="closeNotificationDetail()">
                    <i class="fas fa-times"></i> 关闭
                </button>
                ${!notification.is_read ? `
                <button class="friend-action-btn primary" onclick="markCurrentNotificationAsRead()">
                    <i class="fas fa-check"></i> 标记已读
                </button>
                ` : ''}
            </div>
        </div>

        <div class="chat-messages" id="chat-messages" style="background: white;">
            ${detailContent}
        </div>

        <div class="chat-input-container" style="display: none;">
            <!-- 隐藏输入框 -->
        </div>
    `;

    // 存储当前查看的通知
    window.currentNotification = notification;
}

// 关闭通知详情
function closeNotificationDetail() {
    const chatArea = document.getElementById('chat-area');
    chatArea.classList.add('empty');
    chatArea.innerHTML = `
        <div class="empty-chat">
            <i class="fas fa-comment-dots"></i>
            <h3>选择系统通知</h3>
            <p>从左侧选择一个通知查看详情</p>
        </div>
    `;
    window.currentNotification = null;
}

// 标记当前通知为已读
function markCurrentNotificationAsRead() {
    if (!window.currentNotification) return;

    const notificationId = window.currentNotification.id;
    const notificationElement = document.querySelector(`[data-notification-id="${notificationId}"]`);

    markNotificationAsRead(notificationId, notificationElement);
}

// 更新标记为已读函数
function markNotificationAsRead(notificationId, notificationElement) {
    fetch(`/social/notifications/${notificationId}/mark-read/`, {
        method: 'POST',
        headers: {
            'X-CSRFToken': getCookie('csrftoken'),
            'Content-Type': 'application/json'
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // 更新列表中的显示
            if (notificationElement) {
                notificationElement.classList.remove('unread');
                const badge = notificationElement.querySelector('.unread-badge');
                if (badge) {
                    badge.remove();
                    // 更新红点
                    updateNotificationsBadge();
                }
            }

            // 更新详情页面的显示
            if (window.currentNotification && window.currentNotification.id === notificationId) {
                window.currentNotification.is_read = true;
                const readStatus = document.querySelector('.chat-header-info p');
                if (readStatus) {
                    readStatus.textContent = '已读';
                }
                const markReadBtn = document.querySelector('button[onclick="markCurrentNotificationAsRead()"]');
                if (markReadBtn) {
                    markReadBtn.remove();
                }
            }

            // 更新未读计数
            updateUnreadNotificationCount();
        } else {
            alert('操作失败: ' + data.message);
        }
    })
    .catch(error => {
        console.error('标记已读失败:', error);
        alert('操作失败，请重试');
    });
}

// 更新未读通知计数
function updateUnreadNotificationCount() {
    // 重新加载通知列表来更新计数
    loadSystemNotifications();

    // 同时更新页面上的未读徽章
    fetch('/social/notifications/list/')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const unreadCount = data.notifications.filter(notification => !notification.is_read).length;
                const badge = document.querySelector('.tab-btn[data-tab="notifications"] .unread-badge');
                if (unreadCount > 0) {
                    if (badge) {
                        badge.textContent = unreadCount;
                    } else {
                        // 创建徽章
                        const tabBtn = document.querySelector('.tab-btn[data-tab="notifications"]');
                        const newBadge = document.createElement('span');
                        newBadge.className = 'unread-badge';
                        newBadge.textContent = unreadCount;
                        tabBtn.appendChild(newBadge);
                    }
                } else if (badge) {
                    badge.remove();
                }
            }
        })
        .catch(error => console.error('更新未读计数失败:', error));
}


// 删除全部系统消息
function deleteAllNotifications() {
    // 创建确认模态框
    const confirmModal = document.createElement('div');
    confirmModal.className = 'modal active confirm-modal';
    confirmModal.innerHTML = `
        <div class="modal-content">
            <div class="modal-header">
                <h3>确认删除</h3>
                <button class="modal-close" onclick="closeConfirmModal()">&times;</button>
            </div>
            <div style="padding: 20px 0;">
                <p style="text-align: center; font-size: 16px; color: #333; margin-bottom: 10px;">
                    <i class="fas fa-exclamation-triangle" style="color: #ffa502; font-size: 24px; margin-bottom: 15px; display: block;"></i>
                    确定要删除所有系统消息吗？
                </p>
                <p style="text-align: center; color: #666; font-size: 14px;">
                    此操作不可恢复，所有系统消息将被永久删除。
                </p>
            </div>
            <div class="confirm-actions">
                <button class="confirm-btn cancel" onclick="closeConfirmModal()">
                    <i class="fas fa-times"></i> 取消
                </button>
                <button class="confirm-btn delete" onclick="confirmDeleteAllNotifications()">
                    <i class="fas fa-trash"></i> 确认删除
                </button>
            </div>
        </div>
    `;

    document.body.appendChild(confirmModal);
}

// 关闭确认模态框
function closeConfirmModal() {
    const modal = document.querySelector('.confirm-modal');
    if (modal) {
        modal.remove();
    }
}

// 确认删除全部系统消息
function confirmDeleteAllNotifications() {
    fetch('/social/notifications/delete-all/', {
        method: 'DELETE',
        headers: {
            'X-CSRFToken': getCookie('csrftoken'),
            'Content-Type': 'application/json'
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert(data.message);
            closeConfirmModal();
            // 清空通知列表
            document.getElementById('notifications-list').innerHTML =
                '<div class="empty-conversations"><i class="fas fa-bell"></i><p>暂无系统通知</p></div>';
            // 更新未读计数
            updateUnreadNotificationCount();
            // 如果当前正在查看通知详情，关闭它
            if (window.currentNotification) {
                closeNotificationDetail();
            }
            // 更新红点
            updateNotificationsBadge();
        } else {
            alert('删除失败: ' + data.message);
        }
    })
    .catch(error => {
        console.error('删除全部通知失败:', error);
        alert('操作失败，请重试');
    });
}



// 更新所有标签页的红点状态
function updateAllTabBadges() {
    updateConversationsBadge();
    updateFriendsBadge();
    updateGroupsBadge();
    updateNotificationsBadge();
}

// 更新消息标签红点
function updateConversationsBadge() {
    const badge = document.getElementById('conversations-badge');
    if (!badge) return;

    // 计算所有会话的未读消息总数
    let totalUnread = 0;
    document.querySelectorAll('.conversation-item .unread-badge').forEach(badge => {
        const count = parseInt(badge.textContent) || 1;
        totalUnread += count;
    });

    if (totalUnread > 0) {
        badge.textContent = totalUnread > 99 ? '99+' : totalUnread.toString();
        badge.style.display = 'inline-block';
    } else {
        badge.style.display = 'none';
    }
}

// 更新好友标签红点
function updateFriendsBadge() {
    const badge = document.getElementById('friends-badge');
    if (!badge) return;

    // 获取好友请求数量
    fetch('/social/friends/requests/')
        .then(res => res.json())
        .then(data => {
            if (data.success && data.received.length > 0) {
                badge.textContent = data.received.length > 99 ? '99+' : data.received.length.toString();
                badge.style.display = 'inline-block';
            } else {
                badge.style.display = 'none';
            }
        })
        .catch(error => {
            console.error('获取好友请求数量失败:', error);
            badge.style.display = 'none';
        });
}

// 更新群组标签红点
function updateGroupsBadge() {
    const badge = document.getElementById('groups-badge');
    if (!badge) return;

    // 这里可以添加群组相关的未读消息逻辑
    // 暂时设置为无红点
    badge.style.display = 'none';
}

// 更新系统通知标签红点
function updateNotificationsBadge() {
    const badge = document.getElementById('notifications-badge');
    if (!badge) return;

    fetch('/social/notifications/list/')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const unreadCount = data.notifications.filter(notification => !notification.is_read).length;
                if (unreadCount > 0) {
                    badge.textContent = unreadCount > 99 ? '99+' : unreadCount.toString();
                    badge.style.display = 'inline-block';
                } else {
                    badge.style.display = 'none';
                }
            } else {
                badge.style.display = 'none';
            }
        })
        .catch(error => {
            console.error('获取通知数量失败:', error);
            badge.style.display = 'none';
        });
}


// 静默标记所有通知为已读（不显示提示）
function markAllNotificationsAsReadSilent() {
    fetch('/social/notifications/mark-all-read/', {
        method: 'POST',
        headers: {
            'X-CSRFToken': getCookie('csrftoken'),
            'Content-Type': 'application/json'
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            console.log('所有通知已标记为已读');
            // 更新通知列表的显示状态
            document.querySelectorAll('.conversation-item.unread').forEach(item => {
                item.classList.remove('unread');
                const badge = item.querySelector('.unread-badge');
                if (badge) {
                    badge.remove();
                }
            });
        }
    })
    .catch(error => {
        console.error('标记全部已读失败:', error);
    });
}

// 更新消息标签红点
function updateConversationsDot() {
    const dot = document.getElementById('conversations-dot');
    if (!dot) return;

    // 只有当前不在消息标签页时才显示红点
    const isActive = document.querySelector('.tab-btn[data-tab="conversations"]').classList.contains('active');
    if (isActive) {
        dot.style.display = 'none';
        return;
    }

    // 检查是否有任何会话有未读消息
    let hasUnread = false;
    document.querySelectorAll('.conversation-item .unread-badge').forEach(badge => {
        hasUnread = true;
    });

    dot.style.display = hasUnread ? 'inline-block' : 'none';
}

// 更新好友标签红点
function updateFriendsDot() {
    const dot = document.getElementById('friends-dot');
    if (!dot) return;

    // 只有当前不在好友标签页时才显示红点
    const isActive = document.querySelector('.tab-btn[data-tab="friends"]').classList.contains('active');
    if (isActive) {
        dot.style.display = 'none';
        return;
    }

    // 检查是否有好友请求
    fetch('/social/friends/requests/')
        .then(res => res.json())
        .then(data => {
            if (data.success && data.received.length > 0) {
                dot.style.display = 'inline-block';
            } else {
                dot.style.display = 'none';
            }
        })
        .catch(error => {
            console.error('获取好友请求失败:', error);
            dot.style.display = 'none';
        });
}

// 更新系统通知标签红点
function updateNotificationsDot() {
    const dot = document.getElementById('notifications-dot');
    if (!dot) return;

    // 只有当前不在通知标签页时才显示红点
    const isActive = document.querySelector('.tab-btn[data-tab="notifications"]').classList.contains('active');
    if (isActive) {
        dot.style.display = 'none';
        return;
    }

    fetch('/social/notifications/list/')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const hasUnread = data.notifications.some(notification => !notification.is_read);
                dot.style.display = hasUnread ? 'inline-block' : 'none';
            } else {
                dot.style.display = 'none';
            }
        })
        .catch(error => {
            console.error('获取通知失败:', error);
            dot.style.display = 'none';
        });
}

// 监听全局未读计数更新事件（来自base.html的WebSocket和axios）
window.addEventListener('unreadCountsUpdated', function(event) {
    const data = event.detail;
    console.log('收到未读计数更新:', data);
    
    // 更新消息标签页红点
    const conversationsBadge = document.getElementById('conversations-badge');
    if (conversationsBadge && data.unread_messages > 0) {
        conversationsBadge.textContent = data.unread_messages > 99 ? '99+' : data.unread_messages;
        conversationsBadge.style.display = 'inline-block';
    } else if (conversationsBadge) {
        conversationsBadge.style.display = 'none';
    }
    
    // 更新好友标签页红点
    const friendsBadge = document.getElementById('friends-badge');
    if (friendsBadge && data.friend_requests > 0) {
        friendsBadge.textContent = data.friend_requests > 99 ? '99+' : data.friend_requests;
        friendsBadge.style.display = 'inline-block';
    } else if (friendsBadge) {
        friendsBadge.style.display = 'none';
    }
    
    // 更新群组标签页红点
    const groupsBadge = document.getElementById('groups-badge');
    if (groupsBadge && data.unread_group_messages > 0) {
        groupsBadge.textContent = data.unread_group_messages > 99 ? '99+' : data.unread_group_messages;
        groupsBadge.style.display = 'inline-block';
    } else if (groupsBadge) {
        groupsBadge.style.display = 'none';
    }
    
    // 更新系统通知标签页红点
    const notificationsBadge = document.getElementById('notifications-badge');
    if (notificationsBadge && data.unread_notifications > 0) {
        notificationsBadge.textContent = data.unread_notifications > 99 ? '99+' : data.unread_notifications;
        notificationsBadge.style.display = 'inline-block';
    } else if (notificationsBadge) {
        notificationsBadge.style.display = 'none';
    }
    
    // 如果当前在会话列表标签页，刷新会话列表
    const activeTab = document.querySelector('.tab-btn.active');
    if (activeTab && activeTab.getAttribute('data-tab') === 'conversations' && data.unread_messages > 0) {
        refreshConversations();
    }
});

// 使用axios定期刷新当前标签页内容
setInterval(function() {
    const activeTab = document.querySelector('.tab-btn.active');
    if (!activeTab) return;
    
    const tabName = activeTab.getAttribute('data-tab');
    
    // 使用axios异步刷新
    if (tabName === 'conversations') {
        axios.get('/social/chat/conversations/list/')
            .then(response => {
                if (response.data.success) {
                    updateConversationsList(response.data.conversations);
                }
            })
            .catch(error => console.error('刷新会话列表失败:', error));
    } else if (tabName === 'friends') {
        axios.get('/social/friends/list/')
            .then(response => {
                if (response.data.success) {
                    displayFriendsList(response.data.friends);
                }
            })
            .catch(error => console.error('刷新好友列表失败:', error));
    } else if (tabName === 'groups') {
        axios.get('/social/groups/list/')
            .then(response => {
                if (response.data.success) {
                    displayGroupsList(response.data.groups);
                }
            })
            .catch(error => console.error('刷新群组列表失败:', error));
    } else if (tabName === 'notifications') {
        axios.get('/social/notifications/list/')
            .then(response => {
                if (response.data.success) {
                    displayNotificationsList(response.data.notifications);
                }
            })
            .catch(error => console.error('刷新通知列表失败:', error));
    }
}, 30000); // 每30秒刷新一次

// 解散群组（仅群主）
function dissolveGroup(groupId, groupName) {
    if (!confirm(`确定要解散群组 "${groupName}" 吗？\n\n解散后，所有成员将被移除，群聊记录将被删除，此操作不可恢复！`)) {
        return;
    }
    
    // 二次确认
    if (!confirm('请再次确认：真的要解散这个群组吗？')) {
        return;
    }
    
    fetch(`/social/groups/${groupId}/dissolve/`, {
        method: 'POST',
        headers: {
            'X-CSRFToken': getCookie('csrftoken')
        }
    })
    .then(res => res.json())
    .then(data => {
        if (data.success) {
            alert(data.message);
            closeGroupMembersModal();
            // 关闭当前聊天
            const chatArea = document.getElementById('chat-area');
            chatArea.classList.add('empty');
            chatArea.innerHTML = `
                <div class="empty-chat">
                    <i class="fas fa-comment-dots"></i>
                    <h3>群组已解散</h3>
                    <p>该群组已被解散</p>
                </div>
            `;
            // 刷新群组列表
            loadGroupsList();
            // 切换到群组标签页
            document.querySelector('[data-tab="groups"]').click();
        } else {
            alert('解散失败: ' + data.message);
        }
    })
    .catch(error => {
        console.error('解散群组失败:', error);
        alert('解散失败，请重试');
    });
}

// 删除聊天记录
function deleteChatHistory(conversationId) {
    if (!confirm('确定要删除与该好友的所有聊天记录吗？\n\n此操作不可恢复！')) {
        return;
    }
    
    fetch(`/social/conversations/${conversationId}/delete/`, {
        method: 'POST',
        headers: {
            'X-CSRFToken': getCookie('csrftoken')
        }
    })
    .then(res => res.json())
    .then(data => {
        if (data.success) {
            alert('聊天记录已删除');
            // 清空聊天区域
            const chatArea = document.getElementById('chat-area');
            chatArea.classList.add('empty');
            chatArea.innerHTML = `
                <div class="empty-chat">
                    <i class="fas fa-comment-dots"></i>
                    <h3>选择一个对话</h3>
                    <p>从左侧选择一个联系人开始聊天</p>
                </div>
            `;
            // 刷新对话列表
            window.location.reload();
        } else {
            alert('删除失败: ' + data.message);
        }
    })
    .catch(error => {
        console.error('删除聊天记录失败:', error);
        alert('删除失败，请重试');
    });
}
</script>
{% endblock %}
